package com.hd.trans.utils;

import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class VirtualToast {

    private Handler mHandler = new Handler();
    private View contentView;
    private TextView tvContent;

    private static final long TOAST_TIME_SHORT = 2000;
    private static final long TOAST_TIME_LONG = 3500;

    private Runnable mHideRunnable = ()-> contentView.setVisibility(View.GONE);

    public VirtualToast(TextView tv) {
        this.contentView = tv;
        this.tvContent = tv;
    }

    public VirtualToast(View contentView, TextView tv) {
        this.contentView = contentView;
        this.tvContent = tv;
    }

    public VirtualToast(View contentView, int textId) {
        this.contentView = contentView;
        this.tvContent = contentView.findViewById(textId);
    }

    private void show(String msg,int duration,boolean autoHide){
        mHandler.post(()->{
            tvContent.setText(msg);
            contentView.setVisibility(View.VISIBLE);

            mHandler.removeCallbacks(mHideRunnable);

            if (autoHide) {
                mHandler.postDelayed(mHideRunnable, duration > Toast.LENGTH_SHORT ? TOAST_TIME_SHORT : TOAST_TIME_LONG);
            }
        });
    }

    public void show(String msg,int duration){
        show(msg,duration,true);
    }

    public void show(String msg){
        show(msg,Toast.LENGTH_SHORT);
    }

    public void showLengthLong(String msg){
        show(msg,Toast.LENGTH_LONG);
    }

    public void showAlways(String msg){
        show(msg,Toast.LENGTH_SHORT,false);
    }

    public void cancel(){
        mHandler.removeCallbacks(mHideRunnable);
        mHandler.post(mHideRunnable);
    }

    public void release(){
        mHandler.removeCallbacksAndMessages(null);
    }

}
